package cn.elwy.rcp.kit.intro.handler;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class LoginComposite extends Composite {

    private boolean fAuthenticated;
    private Text userNameText;
    private Text passwordText;
    private Button okButton;
    private Button cancelButton;

    /**
     * Create the composite.
     * @param parent
     * @param style
     */
    public LoginComposite(Composite parent, int style) {
        super(parent, style);
        setLayout(new GridLayout(3, false));

        Label userNameLabel = new Label(this, SWT.NONE);
        userNameLabel.setText("用户名(&U): ");

        userNameText = new Text(this, SWT.BORDER);
        userNameText.setText("admin");
        userNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));

        Label passwordLabel = new Label(this, SWT.NONE);
        passwordLabel.setText("密　码(&P): ");

        passwordText = new Text(this, SWT.BORDER | SWT.PASSWORD);
        passwordText.setText("admin");
        passwordText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
        new Label(this, SWT.NONE);

        okButton = new Button(this, SWT.NONE);
        okButton.setText("登 录(&O)");
        getShell().setDefaultButton(okButton);

        okButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                handleButtonOKWidgetSelected();
            }
        });

        cancelButton = new Button(this, SWT.NONE);
        cancelButton.setText("取 消(&C)");

        cancelButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                cancelHandle();
            }
        });
    }

    private void handleButtonOKWidgetSelected() {
        String username = userNameText.getText();
        String password = passwordText.getText();
        if ((username.length() > 0) && (password.length() > 0)) {
            fAuthenticated = true;
        } else {
            MessageDialog.openError(getShell(), "登录失败！", "用户名或密码错误！");
        }
    }

    /**
     * 取消登录事件
     */
    private void cancelHandle() {
        getShell().getDisplay().close();
        System.exit(0);
    }

    /**
     * 等待执行登录或退出按钮
     */
    public void doEventLoop() {
        Shell splash = getShell();
        while (fAuthenticated == false) {
            if (splash.getDisplay().readAndDispatch() == false) {
                splash.getDisplay().sleep();
            }
        }
    }

    @Override
    protected void checkSubclass() {
    }

}
